package com.lingkang.cpm.config.impl;

import cn.hutool.core.lang.Assert;
import com.lingkang.cpm.entity.CUser;
import com.lingkang.cpm.entity.CUserRole;
import com.lingkang.cpm.pojo.SeUser;
import com.lingkang.cpm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 绫小路
 * @Date 2021/4/1
 */
public class CustomUserDetailsServiceImpl implements UserDetailsService {
  @Autowired
  private UserService userService;

  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    Assert.notBlank(s, "账号不为空！");
    CUser user = userService.get(s);
    if (user == null) {
      throw new UsernameNotFoundException("账号不存在！");
    }
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    List<CUserRole> roles = userService.getRoles(s);
    roles.forEach(r -> {
      //security的验证规则需要ROLE_
      grantedAuthorities.add(new SimpleGrantedAuthority(r.getRoleName()));
    });

    SeUser seUser = new SeUser(s, user.getPassword(), grantedAuthorities);
    seUser.setAvatar(user.getAvatar());
    seUser.setName(user.getName());
    seUser.setSex(user.getSex());
    return seUser;
  }
}
